package com.winit.openapi.isp.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.ContractService;
import com.winit.erp.spi.bpartner.command.ContractCommand;
import com.winit.gfs.spi.EbayTrackingNoQueueService;
import com.winit.gfs.spi.GfsOrderDeliveryService;
import com.winit.gfs.spi.command.AddEbayUploadTrackingNoQueueCommand;
import com.winit.gfs.spi.vo.EbayTrackingNoQueueVo;
import com.winit.oms.spi.isp.ISPOrderService;
import com.winit.gfs.spi.vo.GfsOrderDeliveryVo;

import org.apache.commons.lang3.StringUtils;

import com.winit.oms.spi.isp.command.EbayTrackingNumCommand;
import com.winit.oms.spi.isp.vo.EbayTrackingNumberQueue;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 上传跟踪号处理
 * 
 * @author changhao.liu
 *
 */
@Controller
@RequestMapping(value = "/isp/updTrkNum")
public class UploadTrackingNumberController extends BaseController {


    private static final Logger logger = LoggerFactory.getLogger(UploadTrackingNumberController.class);
    
    @Resource
    private ContractService             agreementService;
    @Resource
    private EbayTrackingNoQueueService  ebayTrackingNoQueueService;
    @Resource
    private GfsOrderDeliveryService  gfsOrderDeliveryService;
    
    
    /**
     * 根据订单号查询上传记录
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryTrkNumByOrderId")
    public String queryTrkNumByOrderId(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        checkIspRight();
        Object obj = requestMsg.getData();
        EbayTrackingNumCommand command = new EbayTrackingNumCommand();
        String storeType = "";
        AddEbayUploadTrackingNoQueueCommand gfsCommand = new AddEbayUploadTrackingNoQueueCommand();
        List<EbayTrackingNoQueueVo> gfsList = new ArrayList<EbayTrackingNoQueueVo>();
        gfsCommand.setCtx(CommandContext.getContext());
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "orderId");
            ValidateUtil.validNotNull(json, "orderNo");
            command.setOrderId(json.getLong("orderId"));
            gfsCommand.setTargetNos(json.getString("orderNo"));
            storeType = json.getString("storeType");
        } else {
            logger.error("字段类型错误!");
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        if (StringUtils.isNotBlank(storeType) && !StringUtils.equalsIgnoreCase(storeType, "ebay")) {
            // 如果电商平台不为空且不为ebay，走Teapplix逻辑
            
            //查询Txnid和店铺账号
            GetByKeyCommand<String> searchCommand = new GetByKeyCommand<String>();
            searchCommand.setSearchKey(gfsCommand.getTargetNos());
            GfsOrderDeliveryVo gfsOrderDeliveryVo = gfsOrderDeliveryService
                .queryGfsOrderDeliveryByWinitOrderCode(searchCommand);
            
            logger.info("根据orderNo[{}]去GFS查询上传跟踪号队列", gfsCommand.getTargetNos());
            gfsList = ebayTrackingNoQueueService.queryTrackingNumberQueueByOrderNo(gfsCommand);

            List<Map<String, Object>> gfsTrackingNumList = new ArrayList<Map<String, Object>>();
            for (EbayTrackingNoQueueVo gfsTrackingNumberQueue : gfsList) {
                Map<String, Object> map = this.buildTeapplixMap(gfsTrackingNumberQueue,
                    storeType,gfsOrderDeliveryVo);
                map.put("order_id", command.getOrderId());
                gfsTrackingNumList.add(map);
            }
            responseMsg.setData(gfsTrackingNumList);

            return SUCCESS;

        } else if (StringUtils.isBlank(storeType) || StringUtils.equalsIgnoreCase(storeType, "ebay")) {
            // 如果电商平台为空或为ebay，默认走ebay逻辑

            logger.info("根据orderNo[{}]去GFS查询上传跟踪号队列", gfsCommand.getTargetNos());
            gfsList = ebayTrackingNoQueueService.queryTrackingNumberQueueByOrderNo(gfsCommand);

            List<Map<String, Object>> gfsTrackingNumList = new ArrayList<Map<String, Object>>();
            for (EbayTrackingNoQueueVo gfsTrackingNumberQueue : gfsList) {
                Map<String, Object> map = this.buildEbayMap(gfsTrackingNumberQueue, storeType);
                map.put("order_id", command.getOrderId());
                gfsTrackingNumList.add(map);
            }
            responseMsg.setData(gfsTrackingNumList);

            return SUCCESS;
        }
        return SUCCESS;
    }

    /**
     * 构建map参数
     * @param ebayTrackingNumberQueue
     * @return Map
     */
    private Map<String, Object> buildEbayMap(EbayTrackingNoQueueVo gfsTrackingNoQueueVo, String storeType){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", gfsTrackingNoQueueVo.getId());
        map.put("order_no", gfsTrackingNoQueueVo.getOrderNo());
        map.put("transaction_id", gfsTrackingNoQueueVo.getTransactionId());
        map.put("item_id", gfsTrackingNoQueueVo.getItemId());
        map.put("user_id", gfsTrackingNoQueueVo.getUserId());
        map.put("tracking_number", gfsTrackingNoQueueVo.getTrackingNo());
        map.put("bpartner_id", gfsTrackingNoQueueVo.getBpartnerId());
        map.put("isshipped", gfsTrackingNoQueueVo.getIsshipped());
        map.put("createdby", gfsTrackingNoQueueVo.getCreatedby());
        map.put("created", gfsTrackingNoQueueVo.getCreated());
        map.put("updetedby", gfsTrackingNoQueueVo.getUpdetedby());
        map.put("updeted", gfsTrackingNoQueueVo.getUpdeted());
        map.put("is_active", gfsTrackingNoQueueVo.getIsActive());
        map.put("is_delete", gfsTrackingNoQueueVo.getIsDelete());
        map.put("status", gfsTrackingNoQueueVo.getStatus());
        map.put("handelTimes", gfsTrackingNoQueueVo.getRunNum());
        map.put("exception", gfsTrackingNoQueueVo.getErrorMsg());
        map.put("carrier", gfsTrackingNoQueueVo.getCarrier());
        map.put("storeType", storeType);
        return map;
    }
    
    /**
     * 构建teapplix map参数
     * @param ebayTrackingNumberQueue
     * @return Map
     */
    private Map<String, Object> buildTeapplixMap(EbayTrackingNoQueueVo gfsTrackingNoQueueVo, String storeType,
                                                 GfsOrderDeliveryVo gfsOrderDeliveryVo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", gfsTrackingNoQueueVo.getId());
        map.put("order_no", gfsTrackingNoQueueVo.getOrderNo());
        map.put("tracking_number", gfsTrackingNoQueueVo.getTrackingNo());
        map.put("bpartner_id", gfsTrackingNoQueueVo.getBpartnerId());
        map.put("isshipped", gfsTrackingNoQueueVo.getIsshipped());
        map.put("createdby", gfsTrackingNoQueueVo.getCreatedby());
        map.put("created", gfsTrackingNoQueueVo.getCreated());
        map.put("updetedby", gfsTrackingNoQueueVo.getUpdetedby());
        map.put("updeted", gfsTrackingNoQueueVo.getUpdeted());
        map.put("is_active", gfsTrackingNoQueueVo.getIsActive());
        map.put("is_delete", gfsTrackingNoQueueVo.getIsDelete());
        map.put("status", gfsTrackingNoQueueVo.getStatus());
        map.put("handelTimes", gfsTrackingNoQueueVo.getRunNum());
        map.put("exception", gfsTrackingNoQueueVo.getErrorMsg());
        map.put("carrier", gfsTrackingNoQueueVo.getCarrier());
        map.put("storeType", storeType);

        //设置Txnid
        if (null == gfsOrderDeliveryVo || StringUtils.isBlank(gfsOrderDeliveryVo.getSellerOrderId())) {
            map.put("Txnid", "");
        } else {
            map.put("Txnid", gfsOrderDeliveryVo.getSellerOrderId());
        }
        // 设置店铺账号
        if (null == gfsOrderDeliveryVo || StringUtils.isBlank(gfsOrderDeliveryVo.getTxStoreKey())) {
            map.put("storeKey", "");
        } else {
            map.put("storeKey", gfsOrderDeliveryVo.getTxStoreKey());
        }

        return map;
    }
    
    /**
     * 构建command参数
     * @param json
     * @return
     */
    private EbayTrackingNumberQueue buildSearchCommand(JSONObject json) {
    	EbayTrackingNumberQueue trkingNumQueue = new EbayTrackingNumberQueue();
        if (json.containsKey("id")) {
        	trkingNumQueue.setId(json.getLong("id"));
        }
        if (json.containsKey("order_id")) {
        	trkingNumQueue.setOrder_id(json.getLong("order_id"));
        }
        if (json.containsKey("transaction_id")) {
        	trkingNumQueue.setTransaction_id((json.getString("transaction_id").trim()));
        }
        if (json.containsKey("item_id")) {
        	trkingNumQueue.setItem_id((json.getString("item_id").trim()));
        }
        if (json.containsKey("user_id")) {
        	trkingNumQueue.setUser_id((json.getString("user_id").trim()));
        }
        if (json.containsKey("tracking_number")) {
        	trkingNumQueue.setTracking_number((json.getString("tracking_number").trim()));
        }
        if (json.containsKey("bpartner_id")) {
        	trkingNumQueue.setBpartner_id((json.getLong("bpartner_id")));
        }
        if (json.containsKey("isshipped")) {
        	trkingNumQueue.setIsshipped((json.getString("isshipped").trim()));
        }
        if (json.containsKey("createdby")) {
        	trkingNumQueue.setCreatedby((json.getString("createdby").trim()));
        }
        if (json.containsKey("created")) {
        	trkingNumQueue.setCreated((json.getDate("created")));
        }
        if (json.containsKey("updetedby")) {
        	trkingNumQueue.setUpdetedby((json.getString("updetedby").trim()));
        }
        if (json.containsKey("updeted")) {
        	trkingNumQueue.setUpdeted((json.getDate("updeted")));
        }
        if (json.containsKey("is_active")) {
        	trkingNumQueue.setIs_active((json.getString("is_active").trim()));
        }
        if (json.containsKey("is_delete")) {
        	trkingNumQueue.setIs_delete((json.getString("is_delete").trim()));
        }
        if (json.containsKey("status")) {
        	trkingNumQueue.setStatus((json.getString("status").trim()));
        }
        if (json.containsKey("handelTimes")) {
        	trkingNumQueue.setHandelTimes((json.getInteger("handelTimes")));
        }
        if (json.containsKey("exception")) {
        	trkingNumQueue.setException((json.getString("exception").trim()));
        }
        if (json.containsKey("carrier")) {
        	trkingNumQueue.setCarrier((json.getString("carrier").trim()));
        }
        return trkingNumQueue;
    }

    // 效验用户是不是isp用户
    public void checkIspRight() {
        ContractCommand command = new ContractCommand();
        command.setBusiType("ISP");
        command.setBpartnerId(Long.parseLong(CommandContext.getContext().getUserId()));
        boolean rightStatus = agreementService.isOpenContract(command);

        if (!rightStatus) {
            throw new ApiException(ErrorCode.USERNAME_ISNOT_ISP_USER);
        }
    }

    /**
     * 重传跟踪号
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/reTryUpdTrkingNum")
    public String reTryUpdTrkingNum(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	try {
			// 效验用户是否是isp业务用户
			checkIspRight();
			Object obj = requestMsg.getData();
			EbayTrackingNumCommand command = new EbayTrackingNumCommand();
			List<EbayTrackingNumberQueue> trkNumQueueList = new ArrayList<EbayTrackingNumberQueue>();
			if (obj instanceof JSONObject) {
			    JSONObject json = (JSONObject) obj;
			    if (json.containsKey("orderId")) {
			    	command.setOrderId(json.getLong("orderId"));
			    }
			    JSONArray array = json.getJSONArray("trkNumQueueList");
			    for (Object item : array) {
			    	JSONObject jsonObject = (JSONObject) item;
			    	EbayTrackingNumberQueue trkingNumQueue = buildSearchCommand(jsonObject);
			    	trkNumQueueList.add(trkingNumQueue);
			    }
			    command.setTrkNumQueueList(trkNumQueueList);
			}  else {
			    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
			}
			command.setCtx(CommandContext.getContext());
			logger.info("重传跟踪号,参数为:"+JSON.toJSONString(command.getTrkNumQueueList()));
		} catch (Exception e) {
			logger.error("重传跟踪号异常",e);
			e.printStackTrace();
			return ERROR;
		}
    	return SUCCESS;
    }

    
}
